package com.soujiayi.activity;


import java.io.File;

import com.soujiayi.net.NetworkUtils;
import com.soujiayi.share.SinaWeiboAPI;
import com.soujiayi.share.TecentWeiboAPI;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.weibo.sdk.android.Oauth2AccessToken;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


public class ShareActivity extends Activity  implements TextWatcher {
	
	private EditText et_share_content;
	private TextView tv_share_size_hint;
	private ImageView iv_share_sina;
	private ImageView iv_share_qq;
	private ScrollView sv_share;
	private boolean isNotFromSetting = false;
	
	private Handler handler;
	
    public OAuthV2 tencent_oAuth;
    
	private DatabaseManager databaseManager = new DatabaseManager(ShareActivity.this);
	
	private int selectedTypeCount = 0;
	private int completeTypeCount = 0;
	private boolean isSinaSuccess = false;
	private boolean isTencentSuccess = false;
	private boolean isSinaSelected = false;
	private boolean isTencentSelected = false;
	
	private ProgressDialog progressDialog;
	
	private String imageUrl = "";
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.share);
		
		isNotFromSetting = this.getIntent().getBooleanExtra(Constants.IS_NOT_FROM_SETTING, false);
		
		et_share_content = (EditText) findViewById(R.id.et_share_content);
		tv_share_size_hint = (TextView) findViewById(R.id.tv_share_size_hint);
		iv_share_sina = (ImageView) findViewById(R.id.iv_share_sina);
		iv_share_qq = (ImageView) findViewById(R.id.iv_share_qq);
		sv_share = (ScrollView) findViewById(R.id.sv_share);
				
		String shareContent = "";
		if(isNotFromSetting){
			imageUrl = this.getIntent().getStringExtra("imageUrl");
			shareContent = this.getIntent().getStringExtra("shareContent");
		}else{
			shareContent = getResources().getString(R.string.share_send_to_sinaweibo_content);
		}
		et_share_content.setText(shareContent);
		if(shareContent.length() >= 140){
			tv_share_size_hint.setText(getResources().getString(R.string.share_size_hint).replace("?","0"));
		}else{
			tv_share_size_hint.setText(getResources().getString(R.string.share_size_hint).replace("?", String.valueOf(140 - shareContent.length())));
		}
		
		et_share_content.addTextChangedListener(this);
		
		sv_share.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et_share_content.getWindowToken(), 0); 
				return false;
			}
		});
		
		handler = new Handler(){
		    @Override
		    public void handleMessage(Message msg) {
		        super.handleMessage(msg);
		        Bundle data = msg.getData();
		        completeTypeCount++;
		        boolean isSuccess = data.getBoolean("isSuccess", false);
		        
		        int apiType = data.getInt("api_type");
		        int functionType = data.getInt("function_type");
		        if(functionType == 1){
		        	if(isSuccess){
		        		iv_share_sina.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_sina_selected));
						User user = (User) data.getSerializable(Constants.SETTINGS_USER_KEY);		
						UserKeeper.keepUser(ShareActivity.this, user, Constants.PREFERENCES_NAME_USER_SINA);
						databaseManager.insertShareUser(user);
		        	}else{
		        		Toast.makeText(ShareActivity.this, ShareActivity.this.getResources().getString(R.string.share_login_failure), Toast.LENGTH_SHORT).show(); 
		        	}
		        }
				if(functionType == 2){
					if(isSuccess){
						if(apiType == 1){
							isSinaSuccess = true;
						}else if(apiType == 2){
							isTencentSuccess = true;
						}
						
					}else{
						if(apiType == 1){
							isSinaSuccess = false;
						}else if(apiType == 2){
							isTencentSuccess = false;
						}
						
					}
					if(completeTypeCount == selectedTypeCount){
						progressDialog.dismiss();
						if(isSinaSelected?isSinaSuccess:true && isTencentSelected?isTencentSuccess:true){
							Toast.makeText(ShareActivity.this, ShareActivity.this.getResources().getString(R.string.share_success), Toast.LENGTH_SHORT).show(); 
							ShareActivity.this.finish();
							if(isNotFromSetting){
								overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
							}else{
								overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
							}
						}else{
							if(isSinaSelected?(!isSinaSuccess):true && isTencentSelected?(!isTencentSuccess):true){
								Toast.makeText(ShareActivity.this, ShareActivity.this.getResources().getString(R.string.share_failure), Toast.LENGTH_SHORT).show(); 
							}else{
								if(isSinaSelected?(!isSinaSuccess):false){
									Toast.makeText(ShareActivity.this, ShareActivity.this.getResources().getString(R.string.share_to_sina_failure), Toast.LENGTH_SHORT).show(); 
								}
								if(isTencentSelected?(!isTencentSuccess):false){
									Toast.makeText(ShareActivity.this, ShareActivity.this.getResources().getString(R.string.share_to_tencent_failure), Toast.LENGTH_SHORT).show(); 
								}
							}
						}
						isSinaSelected = false;
					    isTencentSelected = false;
					}
				}
		    }
		    
		};
	}
	
	public void submit(View view) {
		if(et_share_content.getText() != null && et_share_content.getText().toString() != null && !et_share_content.getText().toString().trim().equals("")){
			
			User sinaUser  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_SINA);
			User tencentUser  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_TENCENT);
			if(sinaUser == null && tencentUser==null){
				Toast.makeText(
						ShareActivity.this,
						ShareActivity.this.getResources().getString(
								R.string.share_please_select_one_type),
						Toast.LENGTH_SHORT).show();
			}else{
				if (NetworkUtils.isNetworkConnected(this)){
					progressDialog = new ProgressDialog(ShareActivity.this);
					progressDialog.setMessage(getResources().getString(R.string.submit_loading));
					progressDialog.setCancelable(false);
					progressDialog.show();
					
					selectedTypeCount = 0;
					completeTypeCount = 0;
					if(sinaUser != null){
						selectedTypeCount ++;
						isSinaSelected = true;
						SinaWeiboAPI sinaWeiboAPI = new SinaWeiboAPI(this, handler);
						Oauth2AccessToken token = new Oauth2AccessToken(sinaUser.getSina_token(), sinaUser.getSina_expires_in());
						if(!isNotFromSetting){
							//app
							sinaWeiboAPI.send(et_share_content.getText().toString(), token,Constants.SHARE_SJY_IMAGE );
						}else{
							//product
							sinaWeiboAPI.send(et_share_content.getText().toString()+"  "+ getResources().getString(R.string.share_share_send_product_sina), token, imageUrl);
						}
					}
					
					if(tencentUser != null){
						selectedTypeCount ++;
						isTencentSelected = true;
						tencent_oAuth = new OAuthV2();
						tencent_oAuth.setAccessToken(tencentUser.getTencent_token());
						tencent_oAuth.setExpiresIn(tencentUser.getTencent_expires_in());
						tencent_oAuth.setClientId(tencentUser.getTencent_clientId());
						tencent_oAuth.setClientIP(tencentUser.getTencent_clientIp());
						tencent_oAuth.setClientSecret(tencentUser.getTencent_clientSecret());
						tencent_oAuth.setScope(tencentUser.getTencent_scope());
						tencent_oAuth.setOauthVersion(tencentUser.getTencent_oauthVersion());
						tencent_oAuth.setOpenid(tencentUser.getTencent_openid());
						tencent_oAuth.setOpenkey(tencentUser.getTencent_openkey());
						tencent_oAuth.setRedirectUri(tencentUser.getTencent_redirectUri());
						TecentWeiboAPI tecentWeiboAPI = new TecentWeiboAPI(tencent_oAuth, handler);
						String content = et_share_content.getText().toString();
						if(!isNotFromSetting){
							//app
			        		String picPath = Environment.getExternalStorageDirectory() +  File.separator + Constants.STORAGECARD_DIR + File.separator + "logo_icon.jpg";
			        		CommonUtils.copyAppPicToSDCard(ShareActivity.this, R.drawable.ic_launcher, picPath);
			        		content = content.replace(getResources().getString(R.string.soujiayi_sina_weibo), getResources().getString(R.string.soujiayi_tencent_weibo));
							tecentWeiboAPI.addPic(content,Constants.SHARE_SJY_IMAGE);
						}else{
							//product
							tecentWeiboAPI.addPic( et_share_content.getText().toString()+"  " +getResources().getString(R.string.share_share_send_product_tencent), imageUrl);
						}
					}
				}else{
					Toast.makeText(
							ShareActivity.this,
							ShareActivity.this.getResources().getString(
									R.string.network_unavailable_message),
							Toast.LENGTH_SHORT).show();
				}
			}

		}else{
			Toast.makeText(
					ShareActivity.this,
					ShareActivity.this.getResources().getString(
							R.string.share_hint),
					Toast.LENGTH_SHORT).show();
		}
	}
	
	public void bindSina(View view) {
		User user  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_SINA);
		if(user == null){
			if (NetworkUtils.isNetworkConnected(this)){
				SinaWeiboAPI sinaWeiboAPI = new SinaWeiboAPI(this, handler);
				sinaWeiboAPI.login();
			}else{
				Toast.makeText(
						this,
						this.getResources().getString(
								R.string.network_unavailable_message),
						Toast.LENGTH_SHORT).show();
			}
		}else{
			iv_share_sina.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_sina_unselected));
			UserKeeper.clear(this, Constants.PREFERENCES_NAME_USER_SINA);
			databaseManager.deleteShareUser(user.getType());
		}
	}
	
	public void bindTencent(View view) {
		User user  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_TENCENT);
		if(user != null){
			iv_share_qq.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_qq_unselected));
			UserKeeper.clear(this, Constants.PREFERENCES_NAME_USER_TENCENT);
			databaseManager.deleteShareUser(user.getType());
		}else{
			if (NetworkUtils.isNetworkConnected(this)){
				tencentLogin();
			}else{
				Toast.makeText(
						this,
						this.getResources().getString(
								R.string.network_unavailable_message),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void tencentLogin(){
		if(tencent_oAuth == null){
			tencent_oAuth=new OAuthV2(Constants.TENCENT_REDIRECT_URL);
			tencent_oAuth.setClientId(Constants.TENCENT_CLIENT_ID);
			tencent_oAuth.setClientSecret(Constants.TENCENT_CLIENT_SECRET);
	        
	        //关闭OAuthV2Client中的默认开启的QHttpClient。
	        OAuthV2Client.getQHttpClient().shutdownConnection();
		}
        Intent intent = new Intent(this, OAuthV2AuthorizeWebView.class);
        intent.putExtra("oauth", tencent_oAuth);
        startActivityForResult(intent,2);  
	}
	
    protected void onActivityResult(int requestCode, int resultCode, Intent data)   {
    	boolean isSuccess = false;
        if (requestCode==2) {
            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {
            	tencent_oAuth=(OAuthV2) data.getExtras().getSerializable("oauth");
                if(tencent_oAuth.getStatus()==0){
                	isSuccess = true;
                	User user = new User();
    				user.setType(Constants.USER_TYPE_TENCENT);
    				user.setTencent_token(tencent_oAuth.getAccessToken());
    				user.setTencent_clientId(tencent_oAuth.getClientId());
    				user.setTencent_clientIp(tencent_oAuth.getClientIP());
    				user.setTencent_clientSecret(tencent_oAuth.getClientSecret());
    				user.setTencent_oauthVersion(tencent_oAuth.getOauthVersion());
    				user.setTencent_openid(tencent_oAuth.getOpenid());
    				user.setTencent_openkey(tencent_oAuth.getOpenkey());
    				user.setTencent_redirectUri(tencent_oAuth.getRedirectUri());
    				user.setTencent_scope(tencent_oAuth.getScope());
    				user.setTencent_expires_in(tencent_oAuth.getExpiresIn());
    				user.setTencent_expires_time(String.valueOf(System.currentTimeMillis() + Long.parseLong(tencent_oAuth.getExpiresIn())*1000));
    				
    				iv_share_qq.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_qq_selected));
    				
    				UserKeeper.keepUser(ShareActivity.this, user, Constants.PREFERENCES_NAME_USER_TENCENT);
    				databaseManager.insertShareUser(user);
                }
            }
        }
        if(!isSuccess){
			Toast.makeText(
					ShareActivity.this,
					ShareActivity.this.getResources().getString(
							R.string.share_setting_failure),
					Toast.LENGTH_SHORT).show();
        }
    }
	
	@Override
	public void afterTextChanged(Editable s) {
		int length = 140 - s.toString().length();
		if(s.toString().length() >= 140){
			length = 0;
		}
		tv_share_size_hint.setText(getResources().getString(R.string.share_size_hint).replace("?", String.valueOf(length)));
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		User sinaUser  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_SINA);
		if(sinaUser != null){
			iv_share_sina.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_sina_selected));
		}else{
			iv_share_sina.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_sina_unselected));
		}
		User tencentUser  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_TENCENT);
		if(tencentUser != null){
			iv_share_qq.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_qq_selected));
		}else{
			iv_share_qq.setImageDrawable(getResources().getDrawable(R.drawable.ic_chk_qq_unselected));
		}
	}
	
	public void back(View view) {
		this.finish();
		if(isNotFromSetting){
			overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
		}else{
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}
	}
	
	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		super.onDestroy();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			if(isNotFromSetting){
				overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
			}else{
				overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			}
			return false;
		}
		return false;
	}
	
}
